package com.xiao.tripmateai.agent;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.extern.slf4j.Slf4j;

/**
 * ReAct (Reasoning and Acting) 模式的代理抽象类
 * 实现了思考-行动的循环模式
 */
@EqualsAndHashCode(callSuper = true)
@Data
@Slf4j
public abstract class ReActAgent extends BaseAgent {

    /**
     * 处理当前状态并决定下一步行动
     *
     * @return 是否需要执行行动，true表示需要执行，false表示不需要执行
     */
    public abstract boolean think(SSEPublisher publisher);

    /**
     * 执行决定的行动
     *
     * @return 行动执行结果
     */
    public abstract String act(SSEPublisher publisher);

    /**
     * 执行单个步骤：思考和行动
     *
     * @param publisher 用于发布事件的SSEPublisher
     * @return 步骤执行结果
     */
    @Override
    public String step(SSEPublisher publisher) {
        StringBuilder stepResult = new StringBuilder();

        try {
            publisher.publish(EVENT_THINKING, "开始思考...");
            boolean shouldAct = think(publisher);
            stepResult.append("思考完成");

            if (!shouldAct) {
                publisher.publish(EVENT_THINKING, "无需行动");
                return stepResult.toString();
            }

            publisher.publish(EVENT_ACTION, "开始执行行动...");
            String actResult = act(publisher);
            stepResult.append(" | 行动结果: ").append(actResult);
            return stepResult.toString();
        } catch (Exception e) {
            publisher.publish(EVENT_ERROR, "步骤执行错误: " + e.getMessage());
            log.error("步骤执行失败", e);
            return "步骤执行失败: " + e.getMessage();
        }
    }

}